package com.piece.module.spider.util;

import com.piece.core.framework.util.string.StringUtil;
import com.piece.module.spider.expression.ExpressionEngine;
import com.piece.module.spider.support.SpiderNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Map;
import java.util.Objects;

/**
 * 表达式执行工具类
 */
@Slf4j
@Component
public class ExpressionUtil {

    /**
     * 选择器
     */
    private static ExpressionEngine engine;

    @Autowired
    private ExpressionUtil(ExpressionEngine engine) {
        ExpressionUtil.engine = engine;
    }

    public static boolean executeCondition(SpiderNode fromNode, SpiderNode node, Map<String, Object> variables) {
        if (null != fromNode) {
            String condition = node.getCondition(fromNode.getNodeId());
            if (StringUtil.isNotEmpty(condition)) {
                Object result = null;
                try {
                    result = engine.execute(condition, variables);
                } catch (Exception e) {
                    log.error("判断{}出错,异常信息：{}", condition, e);
                }
                if (result != null) {
                    boolean isContinue = "true".equals(result) || Objects.equals(result, true);
                    log.debug("判断{}={}", condition, isContinue);
                    return isContinue;
                }
                return false;
            }
        }
        return true;
    }

    public static Object execute(String expression, Map<String, Object> variables) {
        return engine.execute(expression, variables);
    }
}
